﻿using System;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;


namespace EmergencySystem_Police
{
	public partial class TCPServer : Form {

		private Socket m_socket;
		IPEndPoint ipep;
		private Thread m_thread;
		byte[] bytes = new byte[1024];
		public string info;
		Socket client;
		public int cut = 0;
		public int normalIndex = 1;
		public TCPServer()
		{
			CheckForIllegalCrossThreadCalls = false;
			StartServer();
		}

		public void StartServer()
		{
			try
			{
				m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
				ipep = new IPEndPoint(IPAddress.Any, 8080);
				m_socket.Bind(ipep);
				m_socket.Listen(10);
				m_thread = new Thread(new ThreadStart(ServerProc));
				m_thread.IsBackground = true;
				m_thread.Start();
			}

			catch {  }
		}

		private void ServerProc()
		{
			try
			{
				
				LiRe();
			}
			catch (Exception e) { }
		}

		private void LiRe()
		{

			try
			{
				client = m_socket.Accept();
				int byteRcv = client.Receive(bytes);
				string recvbuf = Encoding.UTF8.GetString(bytes, 0, byteRcv);
				
				string path = string.Format(Application.StartupPath + "\\normal\\" + normalIndex +".jpg");
				info  = recvbuf;
				FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);

				int RcvFile;
				while (true)
				{
					RcvFile = client.Receive(bytes);
					if (RcvFile > 0)
					{
						fs.Write(bytes, 0, RcvFile);
					}
					else
					{
						fs.Close();
						cut = 1;
						break;
					}
				}
				
				
			}


			finally
			{
				client.Close();

				m_socket.Close();
				m_socket.Shutdown(SocketShutdown.Both);
			}
		}


	}
}
